//
//  TableCodeTreeViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/22.
//

import UIKit
import MJRefresh
import PKHUD
import Kingfisher

/// 代码列表界面
class TableCodeTreeViewController: BaseViewController {

    var tableTree:UITableView!
    var cellID:String = "tablecodetreecellid"
    var projectModel:ProjectMdoel!
    
    // 根据path来查询代码
    var currentPath:String = ""
    
    // 第一目录的数组
    var codeFolderArray:[CodeFolderModel]?{
        didSet{
            guard codeFolderArray != nil else {
                return
            }
            self.tableTree.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    init(project: ProjectMdoel,path: String) {
        super.init(nibName: nil, bundle: nil)
        self.projectModel = project
        currentPath = path
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    

}

// MARK: - 设置界面
extension TableCodeTreeViewController {
    
    func setupUI(){
        
        self.title = self.currentPath == "" ? "代码" : self.currentPath
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        var frame = view.bounds
        frame.size.height -= Common.topHeight
        self.tableTree = UITableView(frame: frame, style: .plain)
        self.tableTree.delegate = self
        self.tableTree.dataSource = self
        self.tableTree.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
        self.tableTree.separatorStyle = .none
        self.tableTree.register(UINib(nibName: "ProjectNormalTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        view.addSubview(self.tableTree)
        
        let mjHeader = MJRefreshNormalHeader {
            self.loadData()
        }
        mjHeader?.lastUpdatedTimeLabel.isHidden = true
        self.tableTree.mj_header = mjHeader
        mjHeader?.beginRefreshing()
        
        if #available(iOS 13.0, *) {
            tableTree.backgroundColor = Colors.backgroundColor
        }
    }
}

// MARK: - 加载数据
extension TableCodeTreeViewController {
    func loadData(){
        
        DispatchQueue.global().async {
            var url = URLs.DETIAL_URL + self.projectModel.id.description + "/repository/tree"
            var par:[String:Any] = [String:Any]()
//            var par:[String:Any] = ["ref_name":"master"]
            if self.currentPath != "" {
                par["path"] = self.currentPath
                url += "?path=\(self.currentPath)/"
            }
            //"private_token":"",
            let tree_url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
            
            let result:Result<[CodeFolderModel?]> = NetWorkTool.shared.getArrayRequest(url: tree_url, parameters:nil)
                
            DispatchQueue.main.async {
                if result.code == 0 {
                  
                    self.codeFolderArray = result.data as? [CodeFolderModel]
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
                self.tableTree.mj_header.endRefreshing()
            }
        }
    }
}

// MARK: - 表格对代理和数据源方法
extension TableCodeTreeViewController: UITableViewDelegate, UITableViewDataSource {

    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.codeFolderArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! ProjectNormalTableViewCell
        let model = self.codeFolderArray![indexPath.row]
        
        cell.cellNameLabel.text = model.name
        if model.type == "tree" {
            cell.cellImageView.image = UIImage(named: "folder")
        }else {
            cell.cellImageView.image = UIImage(named: "file")
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = self.codeFolderArray![indexPath.row]
        if model.type == "tree" {// 文件夹
            let path = currentPath  + model.name + "/"
            let vc = TableCodeTreeViewController(project: projectModel, path: path)
            self.navigationController?.pushViewController(vc, animated: true)
        }else {// 文件
            openFile(file: model)
        }
    }
    
    // 打开文件
    func openFile(file: CodeFolderModel){
        
        if File.isCodeFile(fileName: file.name) {
            let fileVC = FileContentViewController(pid: self.projectModel, path: self.currentPath, name: file.name)
            self.navigationController?.pushViewController(fileVC, animated: true)
        }else if File.isImageFile(fileName: file.name){
            var url = URLs.HTTPSFIX  + "/" + self.projectModel!.path_with_namespace + "/raw/master/"
            url += "\(self.currentPath)/\(file.name.description)"
            url += "?private_token=\(UserDefaultTools.getToken()?.description ?? "")"
            
            let imageVC = ImagePreviewViewController(url: url)
            imageVC.title = file.name
            self.navigationController?.pushViewController(imageVC, animated: true)
            
        }else {
            
            let alertVc = UIAlertController(title: "提示", message: "使用浏览器打开该文件？", preferredStyle: .alert)
            let noAction = UIAlertAction(title: "否", style: .cancel) { (ac) in }
            let yesAction = UIAlertAction(title: "是", style: .default) { (ac) in
                var url = URLs.HTTPSFIX + self.projectModel.owner.username.description + "/" + self.projectModel.name + "/raw/master/"
                url += "\(self.currentPath)/\(file.name.description)"
                let file_url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
                guard let openUrl = URL(string: file_url!) else {
                    HUD.flash(.label("无法打开文件"), delay: 1.0)
                    return
                }
                
                UIApplication.shared.open(openUrl, options: [:], completionHandler: nil)
            }
            
            alertVc.addAction(noAction)
            alertVc.addAction(yesAction)
            self.present(alertVc, animated: true, completion: nil)
        }
    }
    
}
